<template>
  <a-form-model layout="vertical" ref="ruleForm" :rules="rules" :model="model">
    <z-form-item :datas="fieldArr" :rules="rules" :form="model" :gutter="72" @change="getChange">
      <!--//自定义头像上传-->
      <template slot="slots-avatar">
        <j-image-upload bizPath="scott/pic" v-model="model.avatar" />
      </template>
      <!--//自定义接受戒毒方式及起止时间-->
      <template slot="slots-socialDrugKeywordLists">
        <a-checkbox-group v-model="model.socialDrugKeywordLists" @change="onChange" class="slots-checkbox">
          <template v-for="(item, index) in socialDrugOptions">
            <a-checkbox :value="item.value">
              <span class="label">{{ item.keyword }}</span>
              <a-range-picker v-if="item.value==3" v-model="item.date" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" @change="onChangeCheck(item.value, $event)" />
              <a-range-picker v-if="item.value==1" v-model="item.date" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" @change="onChangeCheck(item.value, $event)" />
              <a-range-picker v-if="item.value==2" v-model="item.date" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" @change="onChangeCheck(item.value, $event)" />
              <span v-if="item.value==4" style="display: inline-flex;">
                <a-range-picker v-model="item.date" format="YYYY-MM-DD" valueFormat="YYYY-MM-DD" @change="onChangeCheck(item.value, $event)" />
                <a-select v-model="item.prisonsType" :options="prisonsTypeOptions" placeholder="请选择监所类型" @change="onChangeCheck(item.value, $event)" style="margin-left:10px;"/>
                <a-input v-model="item.prisonsName"  
                placeholder="请录入监所" @change="onChangeCheck(item.value, $event)" 
                style="margin-left:10px;width:200px;"/>
              </span>
            </a-checkbox>
          </template>
        </a-checkbox-group>
      </template>
    </z-form-item>
  </a-form-model>
</template>

<script>
import { queryDepartByArea } from '@/api/api'
export default {
  props: ['current', 'controlPersonType', 'value'],
  data() {
    return {
      model: {
        socialDrugKeywordLists: []
      },
      fieldArr: [
        { label: '头像上传', prop: 'avatar' },
        { label: '姓名', prop: 'realName', tagType: 'input', span: 6 },
        { label: '别名/绰号', prop: 'nickName', tagType: 'input', span: 6 },
        { label: '性别', prop: 'sex', tagType: 'dict-select', dictCode: 'sex', span: 6 },
        { label: '出生年月', prop: 'birthday', tagType: 'date-picker', format: 'YYYY-MM-DD', span: 6 },
        { label: '身高（cm）', prop: 'height', tagType: 'input', span: 6 },
        { label: '风险类别', prop: 'riskCategory', tagType: 'dict-select', dictCode: 'risk_category', span: 6 },
        { label: '联系电话', prop: 'phone', tagType: 'input', span: 6 },
        { label: '身份证号', prop: 'identityCard', tagType: 'input', span: 6 },
        { label: '人员类型', prop: 'personType', tagType: 'dict-select', dictCode: 'social_person_type', span: 6 },
        { label: '文化程度', prop: 'education', tagType: 'dict-select', dictCode: 'degreeEducation', span: 6 },
        { label: '其他证件类型', prop: 'otherCertificateType', tagType: 'dict-select', dictCode: 'other_certificate_type', span: 6 },
        { label: '其他证件号码', prop: 'otherCertificateNumber', tagType: 'input', span: 6 },
        { label: '婚姻状况', prop: 'marriage', tagType: 'dict-select', dictCode: 'marriage', span: 6 },
        { label: '民族', prop: 'nation', tagType: 'dict-select', dictCode: 'nation', span: 6 },
        { label: '国籍', prop: 'country', tagType: 'dict-select', dictCode: 'country', span: 6 },
        { label: '从业状况', prop: 'workSituation', tagType: 'dict-select', dictCode: 'work_situation', span: 6 },
        { label: '户籍地地区', prop: 'houseLevels', tagType: 'linkage-area', span: 12 },
        { label: '户籍地详址', prop: 'householdAddress', tagType: 'input', span: 6 },
        { label: '户籍地派出所', prop: 'householdPoliceStation', tagType: 'input', disabled: true, span: 6 },
        { label: '居住地地区', prop: 'currentLevels', tagType: 'linkage-area', span: 12 },
        { label: '居住地详址', prop: 'currentAddress', tagType: 'input', span: 6 },
        { label: '居住地派出所', prop: 'currentPoliceStation', tagType: 'input', disabled: true, span: 6 },
        { label: '工作单位', prop: 'workUnit', tagType: 'input', span: 6 },
        { label: '单位电话', prop: 'unitPhone', tagType: 'input', span: 6 },
        { label: '初次吸毒日期', prop: 'firstDrugDate', tagType: 'date-picker', format: 'YYYY-MM-DD', span: 6 },
        { label: '既往戒毒次数', prop: 'abstinenceDrugTimes', tagType: 'input', span: 6 },
        { label: '是否复吸', prop: 'isResorption', tagType: 'dict-select', dictCode: 'dict_yn', span: 6 },
        { label: '管控等级', prop: 'controlLevel', tagType: 'dict-select', dictCode: 'control_level', disabled: true, span: 6 },
        { label: '滥用毒品方式', prop: 'drugWays', tagType: 'dict-multi-tag', dictCode: 'drug_ways', type: 'checkbox' },
        { label: '滥用毒品种类', prop: 'drugType', tagType: 'dict-multi-tag', dictCode: 'drug_type', type: 'checkbox' },
        { label: '接受戒毒方式及起止时间', prop: 'socialDrugKeywordLists' },
      ],
      socialDrugOptions: [
        { keyword: '自愿戒毒', value: 3 },
        { keyword: '社区戒毒', value: 1 },
        { keyword: '社区康复', value: 2 },
        { keyword: '强制隔离戒毒', value: 4 },
        { keyword: '无', value: 5 },
      ],
      prisonsTypeOptions: [],
      prisonsNameOptions: [
        { key: '1', title: '测试' },
        { key: '2', title: '测2试' },
      ],
      rules: {
        // 头像上传
        avatar: [{ required: true, message: '请上传头像', trigger: 'change' },],
        realName: [ { required: true, message: '请输入', trigger: 'change' }, ],
        sjskType: [ { required: true, message: '请选择', trigger: 'change' }, ],
        sjskStartDate: [ { required: true, message: '请选择', trigger: 'change' }, ],
        sjskEndDate: [ { required: true, message: '请选择', trigger: 'change' }, ],
        sex: [ { required: true, message: '请选择', trigger: 'change' }, ],
        birthday: [ { required: true, message: '请选择', trigger: 'change' }, ],
        education: [ { required: true, message: '请选择', trigger: 'change' }, ],
        height: [ { required: true, message: '请输入', trigger: 'change' }, ],
        nation: [ { required: true, message: '请选择', trigger: 'change' }, ],
        country: [ { required: true, message: '请选择', trigger: 'change' }, ],
        identityCard: [ { required: true, message: '请输入', trigger: 'change' }, ],
        personType: [ { required: true, message: '请选择', trigger: 'change' }, ],
        education: [ { required: true, message: '请选择', trigger: 'change' }, ],
        phone: [ { required: true, message: '请输入', trigger: 'change' }, 
                  { validator: this.phonerule }],
        houseLevels: [ { required: true, message: '请选择', trigger: 'change' }, ],
        householdAddress: [ { required: true, message: '请输入', trigger: 'change' }, ],
        householdPoliceStation: [ { required: true, message: '请输入', trigger: 'change' }, ],
        currentLevels: [ { required: true, message: '请选择', trigger: 'change' }, ],
        currentAddress: [ { required: true, message: '请输入', trigger: 'change' }, ],
        currentPoliceStation: [ { required: true, message: '请选择居住地地区', trigger: 'change' }, ],
        marriage: [ { required: true, message: '请选择', trigger: 'change' }, ],
        workSituation: [ { required: true, message: '请选择', trigger: 'change' }, ],
        healthStatus: [ { required: true, message: '请选择', trigger: 'change' }, ],
        isJoinMedicineTreatment: [ { required: true, message: '请选择', trigger: 'change' }, ],
        isIntoRecurePlace: [ { required: true, message: '请选择', trigger: 'change' }, ],
        firstDrugDate: [ { required: true, message: '请选择', trigger: 'change' }, ],
        riskCategory: [ { required: true, message: '请选择', trigger: 'change' }, ],
        isResorption: [ { required: true, message: '请选择', trigger: 'change' }, ],
        abstinenceDrugTimes: [ { required: true, message: '请输入', trigger: 'change' }, ],
        controlLevel: [ { required: true, message: '请选择', trigger: 'change' }, ],
        outDate: [ { required: true, message: '请选择', trigger: 'change' }, ],
        drugWays: [ { required: true, message: '请选择', trigger: 'change' }, ],
        drugType: [ { required: true, message: '请选择', trigger: 'change' }, ],
        socialDrugKeywordLists: [
          { required: true, type: 'array', message: '请选择', trigger: 'change' },
          { validator: this.socialDrugLists }
        ]
      }
    }
  },
  computed: {
    getValue() {
      let value = this.value ? this.value : {}
      return value
    }
  },
  watch: {
    getValue: {
      immediate: true,
      deep: true,
      handler(val) {
        this.model = Object.assign({}, this.model, val)
        if (Object.keys(this.model).length > 0) {
          if (this.model.houseLevel) {
            let houseLevels = this.model.houseLevel ? this.model.houseLevel.split(',') : []
            this.$set(this.model, 'houseLevels', houseLevels)
          }
          if (this.model.currentLevel) {
            let currentLevels = this.model.currentLevel ? this.model.currentLevel.split(',') : []
            this.$set(this.model, 'currentLevels', currentLevels)
          }
          if (this.model.socialDrugKeywordList) {
            let socialDrugKeywordList = this.model.socialDrugKeywordList.map(v => v.value)
            this.$set(this.model, 'socialDrugKeywordLists', socialDrugKeywordList)
            const socialDrugOptions = JSON.parse(JSON.stringify(this.socialDrugOptions))
            this.socialDrugOptions = this.model.socialDrugKeywordList.reduce((acc, cur) => {
              const target = acc.find(e => e.value === cur.value);
              if (target) {
                let date = cur.startDate && cur.endDate ? { date: [cur.startDate, cur.endDate] } : {}
                Object.assign(target, cur, date);
              } else {
                acc.push(cur);
              }
              return acc;
            }, socialDrugOptions);
          }
        }
      }
    },
    // model:{
    //   // immediate: true,
    //   deep: true,
    //   handler(val) {
    //     this.$emit('change', this.current, val)
    //   }
    // }
  },
  mounted() {
    this.initTabTypes()
  },
  methods: {
    onChange(value) {
      let filterOptionsWithDisabled = this.socialDrugOptions.filter(item => value.indexOf(item.value) > -1)
      this.$set(this.model, 'socialDrugKeywordList', filterOptionsWithDisabled)
    },
    onChangeCheck(value, dates, field) {
      if (Array.isArray(dates)) { //选择时间范围执行
        let dataIndex = this.socialDrugOptions.findIndex(item => item.value === value)
        let obj = this.socialDrugOptions[dataIndex]
        this.$set(obj, 'startDate', dates[0])
        this.$set(obj, 'endDate', dates[1])
      }
      let filterOptionsWithDisabled = this.socialDrugOptions.filter(item => this.model.socialDrugKeywordLists.indexOf(item.value) > -1)
      this.$set(this.model, 'socialDrugKeywordList', filterOptionsWithDisabled)
      this.$refs['ruleForm'].validateField('socialDrugKeywordLists')
    },
    getChange(prop, value) {
      console.log(prop)
      console.log(value)
      if (prop === 'riskCategory') {
        this.$set(this.model, 'controlLevel', value)
        this.$refs['ruleForm'].validateField('controlLevel')
      }
      if (prop === 'houseLevels') {
        let lastData = value.length > 0 ? value[value.length - 1] : ''
        let flastData = value.length > 0 ? value[value.length - 2] : ''
        this.$set(this.model, 'houseLevel', value.toString())
        this.$set(this.model, 'houseDepartmentId', lastData)
        if (value && value.length == 5) this.getQueryDepartByArea(flastData, 'houseLevel')
      }
      if (prop === 'currentLevels') {
        let lastData = value.length > 0 ? value[value.length - 1] : ''
        let flastData = value.length > 0 ? value[value.length - 2] : ''
        this.$set(this.model, 'currentLevel', value.toString())
        this.$set(this.model, 'currentDepartmentId', lastData)
        if (value && value.length == 5) this.getQueryDepartByArea(flastData, 'currentLevel')
      }
    },
    // 通过执行社区筛选派出所信息
    getQueryDepartByArea(code, field) {
      queryDepartByArea({ type: 2, code })
        .then(res => {
          if (res.success) {
            const { result } = res
            if (result && Object.keys(result).length > 0 && result.departName) {
              let departName = result.departName
              if (field === 'houseLevel') this.$set(this.model, 'householdPoliceStation', departName)
              if (field === 'currentLevel') this.$set(this.model, 'currentPoliceStation', departName)
            } else {
              if (field === 'houseLevel') this.$set(this.model, 'householdPoliceStation', "")
              if (field === 'currentLevel') this.$set(this.model, 'currentPoliceStation', "")
            }
          } else {
            this.$message.warn(res.message)
          }
        })
        .catch(e => {
          this.$message.warn('请求失败！')
        })
    },
    // 初始化字典项
    initTabTypes() {
      this.$initDictOptions('prisons_type').then((res) => {
        if (res.success) {
          this.prisonsTypeOptions = res.result.map(item => {
            return {
              title: item.label,
              key: Number(item.value)
            }
          })
        }
      })
    },
    // 接受戒毒方式及起止时间项校验
    socialDrugLists(rule, value, callback) {
      // console.log(value)
      const val = 4 //强制隔离戒毒值
      let bool = value.includes(val)
      let col = this.socialDrugOptions.find((col, i) => col.value === val)
      if (bool && col.startDate && col.startDate && col.prisonsType && col.prisonsName) {
        callback()
      } else if (bool && !col.startDate && !col.startDate) {
        callback('强制隔离戒毒项的起止时间不能为空')
      } else if (bool && (!col.prisonsName || !col.prisonsType)) {
        callback('强制隔离戒毒项的监所类型和监所不能为空')
      } else if (!bool && !col.startDate && !col.startDate) {
        callback(col.keyword + '项的起止时间不能为空')
      } else {
        callback('请选择强制隔离戒毒项及起止时间、监所类型、监所名称不能为空')
      }
    },
    phonerule(rule, value, callback){
      let myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
      if(myreg.test(value)){
        callback()
      }
      else{
        callback('不行')
      }
    }
  }
}
</script>

<style scoped lang="less">
.slots-checkbox {
  :deep(&.ant-checkbox-group) {
    .ant-checkbox-wrapper {
      display: flex;
      align-items: center;
      margin-bottom: 16px;
      margin-left: 0;

      .label {
        width: 200px;
        display: inline-block;
      }

      .ant-calendar-picker {
        width: 240px;
        flex: 0 0 240px;
      }

      .ant-select {
        flex: 0 0 200px;
      }
    }
  }
}
</style>
